package com.lagou.edu.demo.controller;

import com.lagou.edu.demo.pojo.Result;
import com.lagou.edu.demo.service.TransferService;
import com.lagou.edu.demo.utils.JsonUtils;
import com.lagou.edu.myspring.annotation.MyAutowired;
import com.lagou.edu.myspring.annotation.MyController;
import com.lagou.edu.myspring.annotation.MyRequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author zhenghao
 */
@MyController
@MyRequestMapping("/transferServlet")
public class TransferController{
    @MyAutowired
    private TransferService transferService;

    @MyRequestMapping("/query")
    public void query(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        // 设置请求体的字符编码
        req.setCharacterEncoding("UTF-8");

        String fromCardNo = req.getParameter("fromCardNo");
        String toCardNo = req.getParameter("toCardNo");
        String moneyStr = req.getParameter("money");
        int money = Integer.parseInt(moneyStr);

        Result result = new Result();

        try {
            // 2. 调用service层方法
            transferService.transfer(fromCardNo,toCardNo,money);
            result.setStatus("200");
        } catch (Exception e) {
            e.printStackTrace();
            result.setStatus("201");
            result.setMessage(e.toString());
        }
        // 响应
        resp.setContentType("application/json;charset=utf-8");
        resp.getWriter().print(JsonUtils.object2Json(result));
    }
}
